import axios from 'axios'
import store from '@/store'
import router from '@/router'

const instance = axios.create({
  // baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net/',
  baseURL: 'https://apipc-xiaotuxian-front.itheima.net/',
  timeout: 5000
})

// 请求参数的函数处理
export default (url, method, submitData) => {
  return instance({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}

// 相应拦截器
instance.interceptors.response.use(res => res.data, err => {
  // 401 状态码，进入该函数
  if (err.response && err.response.status === 401) {
    store.commit('user/setUser', {})
    const fullPath = encodeURIComponent(router.currentRoute.value.fullPath)
    // encodeURIComponent 转换uri编码
    router.push('/login?redirectUrl=' + fullPath)
  }
  return Promise.reject(err)
})

// 请求拦截器
instance.interceptors.request.use(
  confirg => {
    const token = store.state.user.profile.token
    if (token) {
      confirg.headers.Authorization = `Bearer ${token}`
    }
    return confirg
  },
  error => {
    return Promise.reject(error)
  }
)
